package com.rich.common.advice;



import com.rich.common.exception.CustomException;
import com.rich.common.result.CommonResponse;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @Author: guofeng
 * @Date: 2021/07/18/19:04
 * @Description:统一异常处理
 */
//@RestControllerAdvice
public class GlobalExceptionHandlerAdvice {
    /**
     * 空指针异常
     * @param e
     * @return
     */
    @ExceptionHandler(value =NullPointerException.class)
    public CommonResponse exceptionHandler(NullPointerException e){
        return new CommonResponse(500,"空指针异常",null);
    }

    /**
     * 后台数据验证异常
     * @author HanSama
     * @date 2021/7/20 12:00
     * @param e
     * @return com.coco.common.result.CommonResponse
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResponse exceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();

        //获取绑定异常
        BindingResult bindingResult = e.getBindingResult();

        //获取异常信息 并封装map
        HashMap<String, String> errorMap = new HashMap<>(16);
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return new CommonResponse(400,"参数异常",errorMap);
    }


    /**
     * 处理其他异常
     */
    @ExceptionHandler(value = Exception.class)
    public CommonResponse exceptionHandler( Exception e) {

        e.printStackTrace();
        return new CommonResponse(500,e.getMessage(),null);
    }

    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = CustomException.class)
    public CommonResponse exceptionHandler( CustomException e) {
        e.printStackTrace();
        return new CommonResponse(e.getErrorEnum().getErrorCode(),e.getErrorEnum().getErrorMsg(),null);
    }
}